﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
using System.IO;
using MacroApp;
using Utilities;

namespace AutoMail
{
    public partial class FrmAddUser : Form
    {
        public FrmAddUser()
        {
            InitializeComponent();
  
            btnUpdate.Visible = false;
            button1.Visible = false;
            Bind();
        }
        private string m_Income;
        private string m_Outcome;
        private string m_Bakup;
        private string m_mailAddress;
        private string m_newfolder;
       
        private int updateId;
        private static string m_appPath = Path.GetDirectoryName(Application.ExecutablePath);
        private LogService m_log = new LogService(m_appPath);
        private void Bind()
        {
            var dt = MailInfoBUS.getUserMailInfo(Program.UserId);
            listMail.Items.Clear();
            if (dt != null)
            {

                int countRow = dt.Rows.Count;
                for (int index = 0; index < countRow; index++)
                {
                    ListViewItem item = new ListViewItem((index+1).ToString());
                    item.SubItems.Add(dt.Rows[index][0].ToString());
                    item.SubItems.Add(dt.Rows[index][1].ToString());
                    item.SubItems.Add(dt.Rows[index][2].ToString());
                    item.SubItems.Add(dt.Rows[index][3].ToString());
                    item.SubItems.Add(dt.Rows[index][4].ToString());
                    listMail.Items.Add(item);                
                }
            }
        }
        private void renameFolder()
        {
            string folderpath = @"D:\MailsSave\" + m_mailAddress;
            bool next= false;
            while (next == false)
            {
                if (folderpath != m_newfolder)
                {
                    try
                    {
                        if (Directory.Exists(folderpath))
                        {
                            System.IO.Directory.Move(folderpath, m_newfolder);
                            next = true;
                        }
                    }
                    catch
                    {
                        next = false;
                    }
                }
                else
                {
                    break;
                }
            }
        }
        private void saveUser(int update = 0)
        {
            UserDTO user = new UserDTO();
            MailInfoDTO mail = new MailInfoDTO();
            user.Username = txtUser.Text.Trim();
            user.PassWord = txtPass.Text.Trim();
            user.RuleUser = 1;
            user.StatusUser = true;
            if (update == 1)
            {
                user.Id = updateId;
                if (UserBUS.updateUser(user) == true)
                {
                    mail.UserId = Convert.ToInt32(UserBUS.getUserByName(user.Username).Rows[0][0]);
                    mail.MailAddress = loginTextBox.Text.Trim();
                    mail.PassWord = Functions.Encrypt(passwordTextBox.Text.Trim(), true);
                    mail.MailServer = popServerTextBox.Text.Trim();
                    mail.Port = portTextBox.Text.Trim();
                    mail.TimeOut = txtTimeout.Text.Trim();
                    mail.RepettionTime = txtRepettion.Text.Trim();
                    if (useSslCheckBox.Checked)
                    {
                        mail.SSl = true;
                    }
                    else
                    {
                        mail.SSl = false;
                    }
                    mail.FolderIncome = string.Format(@"{0}", txtDataFoder.Text.Trim());
                    mail.FolderOutcome = string.Format(@"{0}", txtOutCome.Text.Trim());
                    mail.FolderBackup = string.Format(@"{0}", txtBackUp.Text.Trim());
                    mail.PassWordExcel = txtPassWordExcel.Text.Trim();
                    mail.MesseageMail = txtMailInfo.Text.Trim();
                    mail.Ext = rtxExt.Text;
                    if (MailInfoBUS.updateMailInfo(mail) == false)
                    {
                        return;
                    }
                    
                    renameFolder();
                    m_Income = string.Format(@"{0}", txtDataFoder.Text.Trim());
                    m_Outcome = string.Format(@"{0}", txtOutCome.Text.Trim() );
                    m_Bakup = string.Format(@"{0}", txtBackUp.Text.Trim());
                    m_mailAddress = string.Format(@"{0}\{1}", txtDataFoder.Text.Trim(),loginTextBox.Text.Trim());
                    CreatePath();
                    string path = string.Format(@"{0}", txtBackUp.Text.Trim()) + @"\MailInfoDefault.txt";
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    using (FileStream fs = File.Create(path))
                    {
                        Byte[] info = new UTF8Encoding(true).GetBytes(mail.MesseageMail);
                        fs.Write(info, 0, info.Length);
                    }
                    MessageBox.Show("Update successfuly!");
                    return;
                }
            }
            else if(updateId ==0)
            {
                if (UserBUS.insertUser(user) == true)
                {
                    mail.UserId =  Convert.ToInt32(UserBUS.getUserLast().Rows[0][0]);
                    mail.MailAddress = loginTextBox.Text.Trim();
                    mail.PassWord = Functions.Encrypt(passwordTextBox.Text.Trim(), true);
                    mail.MailServer = popServerTextBox.Text.Trim();
                    mail.Port = portTextBox.Text.Trim();
                    mail.TimeOut = txtTimeout.Text.Trim();
                    mail.RepettionTime = txtRepettion.Text.Trim();
                    if (useSslCheckBox.Checked)
                    {
                        mail.SSl = true;
                    }
                    else
                    {
                        mail.SSl = false;
                    }
                    mail.FolderIncome = txtDataFoder.Text.Trim() + @"\" + mail.MailAddress + @"\Income";
                    mail.FolderOutcome = txtOutCome.Text.Trim() + @"\" + mail.MailAddress + @"\Outcome";
                    mail.FolderBackup = txtBackUp.Text.Trim() + @"\" + mail.MailAddress + @"\Bakup";
                    mail.PassWordExcel = txtPassWordExcel.Text.Trim();
                    mail.MesseageMail = txtMailInfo.Text.Trim();
                    mail.Ext = rtxExt.Text;
                    if (MailInfoBUS.insertMailInfo(mail) == false)
                    {
                        return;
                    }
                    m_Income = string.Format(@"{0}", txtDataFoder.Text.Trim() + @"\" + mail.MailAddress) + @"\Income";
                    m_Outcome = string.Format(@"{0}", txtOutCome.Text.Trim() + @"\" + mail.MailAddress) + @"\Outcome";
                    m_Bakup = string.Format(@"{0}", txtBackUp.Text.Trim() + @"\" + mail.MailAddress) + @"\Bakup";
                    m_mailAddress = string.Format(@"{0}\{1}\{2}\{3}", txtDataFoder.Text.Trim(), mail.MailAddress, "Income", loginTextBox.Text.Trim());
                    CreatePath();
                    string path = string.Format(@"{0}", txtBackUp.Text.Trim() + @"\" + mail.MailAddress) + @"\Bakup\MailInfoDefault.txt";
                    using (FileStream fs = File.Create(path))
                    {
                        Byte[] info = new UTF8Encoding(true).GetBytes(mail.MesseageMail);
                        fs.Write(info, 0, info.Length);
                    }
                    MessageBox.Show("successfuly!");
                }
            }
          
           
        }
        private bool CreatePath()
        {
            try
            {

                if (!Directory.Exists(m_Income))
                {
                    Directory.CreateDirectory(m_Income);
                }

                if (!Directory.Exists(m_Outcome))
                {
                    Directory.CreateDirectory(m_Outcome);
                }

                if (!Directory.Exists(m_Bakup))
                {
                    Directory.CreateDirectory(m_Bakup);
                }
                if (!Directory.Exists(m_mailAddress))
                {
                    Directory.CreateDirectory(m_mailAddress);
                }
                return true;
            }
            catch (Exception ex)
            {
                m_log.WriteToLog(string.Format(@"{0} Create foldel Error with subject {1}.", DateTime.Now, ex.Message), LogMessageType.Error);
                return false;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!Functions.IsValidEmail(loginTextBox.Text))
            {
                MessageBox.Show("Email Error!", "Mail Receive");
                return;
            }
            if (txtUser.Text.Length == 0)
            {
                MessageBox.Show("Username not empty!","Username Receive");
                return;
            }
            if (txtPass.Text.Length == 0)
            {
                MessageBox.Show("Pass not empty!", "Username Receive");
                return;
            }
            if (!Functions.isInt(portTextBox.Text.Trim()))
            {
                MessageBox.Show("Port must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtRepettion.Text.Trim()))
            {
                MessageBox.Show("Repetition time must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtTimeout.Text.Trim()))
            {
                MessageBox.Show("Timeout must be a number!", "Mail Receive");
                return;
            }
            if (txtDataFoder.Text.Length == 0)
            {
                MessageBox.Show("Data Folder need to enter!", "Mail Receive");
                return;
            }
            if (passwordTextBox.Text.Length == 0)
            {
                MessageBox.Show("Data Folder need to enter!", "Mail Receive");
                return;
            }
            if (MailInfoBUS.getMailInfoByMailAddress(loginTextBox.Text.Trim()).Rows.Count>0)
            {
                MessageBox.Show("Địa chỉ mail  đã tồn tại");
                return;
            }
         
            saveUser();
            Bind();
        }

        private void btncancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void listMail_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listMail.SelectedItems.Count > 0)
            {
                loadInfo(listMail.SelectedItems[0].SubItems[2].Text);
                btnUpdate.Visible = true;
                button1.Visible = true;
            }
          //  System.IO.Directory.Move(@"D:\MailsSave\ducngoc55@yahoo.com.vn", @"D:\MailsSave\ducngoc55");
        }
        private void loadInfo(string email)
        {
              var dt = MailInfoBUS.getMailInfoByMailAddress(email);
              var user = UserBUS.getUserByid(Convert.ToInt32(dt.Rows[0][1]));// UserBUS.getUserByName(username);
                updateId = Convert.ToInt32(user.Rows[0][0]);
                //var dt = MailInfoBUS.getMailInfoById(updateId);
                m_mailAddress = dt.Rows[0][2].ToString(); 
                txtUser.Text = user.Rows[0][1].ToString();
                txtUser.Enabled = false;
                txtPass.Enabled = false;
                txtPass.Text = user.Rows[0][2].ToString();
                loginTextBox.Text = dt.Rows[0][2].ToString();
                passwordTextBox.Enabled = true;
                passwordTextBox.Text = Functions.Decrypt(dt.Rows[0][3].ToString(), true);
                popServerTextBox.Text = dt.Rows[0][4].ToString();
                portTextBox.Text = dt.Rows[0][5].ToString();
                txtTimeout.Text = dt.Rows[0][6].ToString();
                txtRepettion.Text = dt.Rows[0][11].ToString();
                useSslCheckBox.Checked = Convert.ToBoolean(dt.Rows[0][7]);
                txtDataFoder.Text = dt.Rows[0][8].ToString();
                txtOutCome.Text = dt.Rows[0][9].ToString();
                txtBackUp.Text = dt.Rows[0][10].ToString();
                txtPassWordExcel.Enabled = false;
                txtPassWordExcel.Text = dt.Rows[0][12].ToString();
                rtxExt.Text = dt.Rows[0][14].ToString();
                //txtMailInfo.Enabled = false;
                string[] lines;
                string file = txtBackUp.Text + @"\" + "MailInfoDefault.txt";// Path.Combine(m_appPath, @"MailInfoDefault.txt");
                if (File.Exists(file))
                {
                    lines = File.ReadAllLines(file);
                   
                    if (lines.Length > 1)
                    {
                        Functions.AddColouredText(ConvertArrayToString(lines, 0), txtMailInfo);
                    }
                   
                }
                
            

        }
        private string ConvertArrayToString(string[] arr, int Position)
        {
            StringBuilder sw = new StringBuilder();
            for (int i = Position; i < arr.Length; i++)
            {
                {
                    sw.Append(string.Format(@" {0} ", arr[i]) + "\n");
                }
            }
            return sw.ToString();
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!Functions.IsValidEmail(loginTextBox.Text))
            {
                MessageBox.Show("Email Error!", "Mail Receive");
                return;
            }
            if (txtUser.Text.Length == 0)
            {
                MessageBox.Show("Username not empty!", "Username Receive");
                return;
            }
            if (txtPass.Text.Length == 0)
            {
                MessageBox.Show("Pass not empty!", "Username Receive");
                return;
            }
            if (!Functions.isInt(portTextBox.Text.Trim()))
            {
                MessageBox.Show("Port must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtRepettion.Text.Trim()))
            {
                MessageBox.Show("Repetition time must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtTimeout.Text.Trim()))
            {
                MessageBox.Show("Timeout must be a number!", "Mail Receive");
                return;
            }
            if (txtDataFoder.Text.Length == 0)
            {
                MessageBox.Show("Data Folder need to enter!", "Mail Receive");
                return;
            }
            saveUser(1);
            Bind();
        }

        private void btnclear_Click(object sender, EventArgs e)
        {
            updateId = 0;
            txtUser.Enabled = true;
            txtUser.Text = "";
            txtPass.Enabled = true;
           // txtPass.Text = "";
            txtPassWordExcel.Text = "";
            passwordTextBox.Text = "-1";
            loginTextBox.Text = "";
            txtPassWordExcel.Enabled = true;
            txtDataFoder.Text = @"D:\MailsSave";
            txtOutCome.Text= @"D:\MailsSave";
            txtBackUp.Text = @"D:\MailsSave";
            txtMailInfo.Enabled = true;
            txtMailInfo.Text = "Phòng kế toán - Công ty Tư vấn kế toán Hoàng Gia http://thanhlapcongty.com.vn -  Công ty tư vấn kế toàn Hoàng Gia kính gởi quý khách hàng, xin vui lòng xem các nội dung đính kèm, xin cảm ơn.";
            btnUpdate.Visible = false;
            button1.Visible = false;
        }

        private void loginTextBox_TextChanged(object sender, EventArgs e)
        {
            if(Functions.IsValidEmail(loginTextBox.Text.Trim()))
            {
                txtUser.Text = loginTextBox.Text.Trim().Substring(0,loginTextBox.Text.LastIndexOf("@"));
                if (updateId > 0)
                {
                    m_newfolder = @"D:\MailsSave\" + loginTextBox.Text.Trim();
                    txtDataFoder.Text = m_newfolder + @"\Income";
                    txtBackUp.Text = m_newfolder + @"\Bakup";
                    txtOutCome.Text = m_newfolder + @"\Outcome";
            
                }

            }
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult dialogresult = MessageBox.Show("Cảnh báo", "Bạn có muốn xóa", MessageBoxButtons.YesNo);
            if (dialogresult == DialogResult.Yes)
            {
                if (UserBUS.deleteUser(updateId) != true)
                {
                  
                    MessageBox.Show("xảy ra lỗi khi xóa");
                }
                else
                {
                    MailInfoBUS.deleteMailinfo(updateId);
                    Bind();
                }
            }
     
        }
    }
}
